package com.headwind.logistics.system.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import com.headwind.logistics.common.pojo.Coupon;
import com.headwind.logistics.common.pojo.Customer;
import com.headwind.logistics.common.util.RedisUtils;
import com.headwind.logistics.system.dto.CouponCustomerUsedto;
import com.headwind.logistics.system.mapper.CouponMapper;
import com.headwind.logistics.system.service.intl.CouponServiceIntl;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 桂祥宇
 * @Date 2020/7/17 0017 14:52
 * @Version 1.0
 * @DESCRIPTION 优惠券业务逻辑层实现类
 */

@Service
public class CouponServiceImpl implements CouponServiceIntl {

    //访问优惠券数据访问层
    @Resource
    private CouponMapper couponMapper;

    @Resource
    private RedisUtils redisUtils;
    /**
     * 查询所有优惠券
     * @param page 页码
     * @param rows 行数
     * @return
     */
    @Override
    public List<CouponCustomerUsedto> queryAllCouponCustomerUsedto(Integer page, Integer rows){

        if (page != null){
            page = (page-1)*rows;
        }
        return couponMapper.queryAllCouponCustomerUsedto(page,rows);
    }

    /**
     * 根据id删除优惠券
     * @param id 优惠券ID
     * @return
     */
    @Override
    public int deleteCoupon(Long id){
        int count =couponMapper.deleteCoupon(id);
        return count;
    }

    /**
     * 新增优惠券
     * @param coupon 优惠券对象
     * @return
     */
    @Override
    public int addCoupon(Coupon coupon){

        int count =couponMapper.addCoupon(coupon);

        String aer= String.valueOf(coupon.getId());
        String dateTime =coupon.getExpire();
        String ex="优惠卷名称:"+coupon.getName()+"优惠卷过期时间:"+coupon.getExpire()+"获得者:"+coupon.getCustomerId();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // new Date()为获取当前系统时间
        String are=format.format(new Date());
        Date date1 = null;
        Date date2 = null;


        try {
            date1 = format.parse(are);
            date2 = format.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long a =(date2.getTime() - date1.getTime())/1000;

       if (count > 0){
            redisUtils.set(aer,ex,a, TimeUnit.SECONDS);
        }

        return  count;
    }


    /**
     * 查询用户信息
     * @return
     */
    @Override
    public List<Customer> queryAllCustomer(){
        List<Customer> customers=couponMapper.queryAllCustomer();
        return customers;
    }

    /**
     * 修改优惠券生效状态
     * @param
     * @return
     */
    @Override
    public  int updateCustomer(int id){
        int count =couponMapper.updateCustomer(id);
        return count;
    }
}
